#include <iostream>
using std::cout;
using std::endl;
using std::string;

class SafeFile
{
public:
    SafeFile(FILE * fp)
    : _fp(fp)
    {   cout << "SafeFile(FILE *)" << endl; }

    void write(const string & msg)
    {
        fwrite(msg.c_str(), 1, msg.size(), _fp);
    }

    ~SafeFile()
    {
        if(_fp) {
            fclose(_fp);
            cout << ">> fclose(fp)" << endl;
        }
        cout << "~SafeFile()" << endl;
    }

private:
    FILE * _fp;
};

void test0()
{
    //申请资源
    SafeFile sf(fopen("test.txt", "a+"));
    string msg("this is a test\n");
    //执行写操作
    sf.write(msg);
}


int main()
{
    test0();
    return 0;
}

